Total Complexity | 3 |
Total Lines | 29 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | import * as crypto from 'crypto'; |
||
5 | |||
6 | @Injectable() |
||
7 | export class FileEncryptionAdapter implements IFileEncryption { |
||
8 | constructor(private readonly configService: ConfigService) {} |
||
9 | |||
10 | public async encrypt(buffer: Buffer): Promise<Buffer> { |
||
11 | const iv = crypto.randomBytes(16); |
||
12 | const key = await this.getEncryptionKey(); |
||
13 | const cipher = crypto.createCipheriv('aes-256-ctr', key, iv); |
||
14 | |||
15 | return Buffer.concat([iv, cipher.update(buffer), cipher.final()]); |
||
16 | } |
||
17 | |||
18 | public async decrypt(buffer: Buffer): Promise<Buffer> { |
||
19 | const key = await this.getEncryptionKey(); |
||
20 | const iv = buffer.slice(0, 16); |
||
21 | const decipher = crypto.createDecipheriv('aes-256-ctr', key, iv); |
||
22 | |||
23 | return Buffer.concat([decipher.update(buffer.slice(16)), decipher.final()]); |
||
24 | } |
||
25 | |||
26 | private async getEncryptionKey(): Promise<string> { |
||
27 | const key = await this.configService.get<string>('FILE_ENCRYPTION_KEY'); |
||
28 | |||
29 | return crypto |
||
30 | .createHash('sha256') |
||
31 | .update(key) |
||
32 | .digest('base64') |
||
33 | .substr(0, 32); |
||
34 | } |
||
36 |